<template>
  <div class="reservation-container">
    <!-- 页面标题：简化布局，移除状态筛选 -->
    <div class="page-header">
      <h1 class="page-title">我的预定</h1>
      <!-- 可添加刷新按钮，方便手动刷新数据 -->
      <el-button 
        size="small" 
        type="primary" 
        icon="el-icon-refresh"
        @click="fetchReservationData()"
      >
        刷新列表
      </el-button>
    </div>

    <!-- 预定列表：加载状态 + 列表展示 -->
    <div 
      class="reservation-list" 
      v-loading="loading" 
      element-loading-text="加载预定数据中..."
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <!-- 预定项卡片 -->
      <el-card 
        v-for="item in reservations" 
        :key="item.reservationId" 
        class="reservation-card"
      >
        <div class="card-body">
          <!-- 设备图片 + 基本信息 -->
          <div class="equipment-info">
            <el-image 
              :src="getEquipmentCover(item.equipment)" 
              class="equipment-img"
              fit="cover"
              fallback-src="https://picsum.photos/seed/equipment/120/120"
              preview-src-list="[getEquipmentCover(item.equipment)]"
            />
            <div class="equipment-detail">
              <h3 class="equipment-name">{{ item.equipment.brand }} {{ item.equipment.model }}</h3>
              <div class="equipment-meta">
                <span class="meta-item">设备ID：{{ item.equipment.equipmentId }}</span>
                <span class="meta-item">年份：{{ item.equipment.year || '未知' }}</span>
                <span class="meta-item">工作小时：{{ item.equipment.hour || 0 }}h</span>
                <span class="meta-item">所在地：{{ item.equipment.location || '未知' }}</span>
              </div>
            </div>
          </div>

          <!-- 预定信息 + 删除按钮：横向布局，按钮靠右 -->
          <div class="reservation-content">
            <div class="reservation-info">
              <div class="info-row">
                <span class="info-label">预定编号：</span>
                <span class="info-value">{{ item.reservationId }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">预定时间：</span>
                <span class="info-value">{{ formatDate(item.createTime) }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">定金金额：</span>
                <span class="info-value amount">¥{{ (item.reservationDeposit || 0).toFixed(2) }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">支付状态：</span>
                <span class="info-value">
                  <el-tag :type="getStatusTagType(item.reservationStatus)">
                    {{ getStatusText(item.reservationStatus) }}
                  </el-tag>
                </span>
              </div>
              <div class="info-row" v-if="item.reservationStatus === 1">
                <span class="info-label">定金支付时间：</span>
                <span class="info-value">{{ formatDate(item.depositPayTime) }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">预定有效期：</span>
                <span class="info-value" :class="isExpired(item.expireTime) ? 'expired' : ''">
                  {{ formatDate(item.expireTime) }}
                  <span v-if="isExpired(item.expireTime) && item.reservationStatus !== 4" class="expire-tag">已过期</span>
                </span>
              </div>
            </div>

            <!-- 优化删除按钮：独立区域，样式更醒目 -->
            <div class="action-area">
              <el-button 
                size="small" 
                type="danger" 
                icon="el-icon-delete"
                @click="handleDeleteReservation(item.reservationId)"
                class="delete-btn"
                :disabled="[1,2].includes(item.reservationStatus)"  
              >
                删除预定
              </el-button>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 空状态：无预定数据时显示 -->
      <el-empty 
        v-if="reservations.length === 0 && !loading" 
        description="暂无相关预定记录"
        class="empty-state"
      >
        <template #image>
          <img 
            src="https://picsum.photos/seed/empty/200/200" 
            alt="无数据" 
            class="empty-img"
          />
        </template>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useCounterStore } from '@/stores/counter';
// 导入 Element Plus 组件和样式
import { ElMessage, ElMessageBox, ElTag, ElImage, ElButton, ElCard, ElEmpty } from 'element-plus';
import 'element-plus/dist/index.css';

// 状态管理
const counterStore = useCounterStore();
const loading = ref(false); // 加载状态
const reservations = ref([]); // 所有预定数据

// 初始化加载预定数据
onMounted(() => {
  fetchReservationData();
});

/**
 * 获取预定数据
 */
async function fetchReservationData() {
  try {
    loading.value = true;
    const res = await axios.get(`/eduservice/equipmentReservation/getAllByUId/${counterStore.userId}`);
    
    if (res.data?.code === 20000 && res.data.data?.list) {
      reservations.value = res.data.data.list; // 赋值预定列表
      console.log("获取预定数据成功：", reservations.value);
      console.log("预定总数：", res);
    } else {
      ElMessage.error("获取预定数据失败：" + (res.data?.message || "未知错误"));
      reservations.value = [];
    }
  } catch (error) {
    console.error("请求预定数据异常：", error);
    ElMessage.error("网络异常，请稍后重试");
    reservations.value = [];
  } finally {
    loading.value = false;
  }
}

/**
 * 获取设备封面图（优先取isCover=true的图片）
 */
const getEquipmentCover = (equipment) => {
  if (!equipment?.equipmentImages || equipment.equipmentImages.length === 0) {
    return "https://picsum.photos/seed/equipment/120/120";
  }
  // 查找封面图，无则取第一张
  const coverImg = equipment.equipmentImages.find(img => img.isCover);
  return coverImg ? coverImg.imageUrl : equipment.equipmentImages[0].imageUrl;
};

/**
 * 格式化日期时间（兼容ISO格式和空值）
 */
const formatDate = (dateStr) => {
  if (!dateStr) return "暂无时间";
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return "无效时间";
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

/**
 * 判断预定是否过期（仅用于未标记为4-已过期状态的记录）
 */
const isExpired = (expireTime) => {
  if (!expireTime) return false;
  const now = new Date();
  const expireDate = new Date(expireTime);
  return now > expireDate;
};

/**
 * 获取预定状态文本（补充所有状态：0-4）
 */
const getStatusText = (status) => {
  const statusMap = {
    0: "待支付押金",
    1: "已支付押金",
    2: "已转订单",
    3: "已取消",
    4: "已过期"
  };
  return statusMap[status] || "未知状态";
};

/**
 * 获取状态标签类型（为每个状态分配对应样式）
 */
const getStatusTagType = (status) => {
  const typeMap = {
    0: "warning",    // 待支付押金 - 警告色
    1: "success",    // 已支付押金 - 成功色
    2: "primary",    // 已转订单 - 主色调
    3: "danger",     // 已取消 - 危险色
    4: "info"        // 已过期 - 信息色
  };
  return typeMap[status] || "default";
};

/**
 * 删除预定：调用后端DELETE接口 /eduservice/equipmentReservation/deleteById/{id}
 */
const handleDeleteReservation = (reservationId) => {
  ElMessageBox.confirm(
    `确定删除预定编号 ${reservationId} 吗？删除后数据将无法恢复`,
    "删除确认",
    { 
      confirmButtonText: "确认删除", 
      cancelButtonText: "取消", 
      type: "danger",
      center: true
    }
  ).then(async () => {
    try {
      // 调用后端删除接口（DELETE请求）
      const res = await axios.delete(`/eduservice/equipmentReservation/deleteById/${reservationId}`);
      
      // 根据后端返回success字段判断删除结果
      if (res.data?.success) {
        ElMessage.success("预定删除成功");
        fetchReservationData(); // 重新加载预定列表，更新页面
      } else {
        ElMessage.error("删除失败：" + (res.data?.message || "服务器异常"));
      }
    } catch (error) {
      console.error("删除预定请求异常：", error);
      ElMessage.error("网络异常，删除失败，请稍后重试");
    }
  }).catch(() => {
    ElMessage.info("已取消删除操作");
  });
};
</script>

<style scoped>
/* 基础容器样式：增加背景色，提升层次感 */
.reservation-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: calc(100vh - 48px);
  background-color: #fafafa;
}

/* 页面头部：简化布局，增加间距 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 28px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

/* 预定列表：调整卡片间距 */
.reservation-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 空状态样式：优化居中效果 */
.empty-state {
  margin: 80px auto;
  text-align: center;
}

.empty-img {
  width: 160px;
  height: 160px;
  border-radius: 50%;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 预定卡片：优化阴影和内边距 */
.reservation-card {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  border-radius: 10px;
  overflow: hidden;
  border: none;
}

.card-body {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 设备信息：保持原有布局 */
.equipment-info {
  display: flex;
  align-items: flex-start;
  gap: 18px;
}

.equipment-img {
  width: 130px;
  height: 130px;
  border-radius: 8px;
  object-fit: cover;
}

.equipment-detail {
  flex: 1;
}

.equipment-name {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0 0 14px 0;
}

.equipment-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 20px;
  font-size: 14px;
  color: #666;
}

/* 预定内容 + 删除按钮：横向布局，按钮固定位置 */
.reservation-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-top: 12px;
  border-top: 1px dashed #eee;
}

.reservation-info {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 30px;
  width: calc(100% - 140px);
}

.info-row {
  display: flex;
  align-items: center;
  font-size: 14px;
  min-width: 220px;
}

.info-label {
  width: 110px;
  color: #666;
  font-weight: 500;
}

.info-value {
  color: #333;
  flex: 1;
}

.amount {
  color: #f56c6c;
  font-weight: 500;
  font-size: 15px;
}

.expired {
  color: #f56c6c;
}

.expire-tag {
  margin-left: 8px;
  font-size: 12px;
  color: #f56c6c;
  background-color: rgba(245, 108, 108, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}

/* 操作区域：删除按钮样式优化 */
.action-area {
  width: 130px;
  text-align: right;
}

.delete-btn {
  width: 100%;
  padding: 8px 0;
  background-color: #fef0f0;
  border-color: #fecdd3;
  color: #ef4444;
  transition: all 0.3s;
}

.delete-btn:hover {
  background-color: #fef0f0;
  border-color: #f87171;
  color: #dc2626;
}

.delete-btn:disabled {
  background-color: #f9fafb;
  border-color: #e5e7eb;
  color: #9ca3af;
  cursor: not-allowed;
}

/* 响应式适配：移动端调整布局 */
@media (max-width: 768px) {
  .reservation-container {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .equipment-img {
    width: 100px;
    height: 100px;
  }

  .reservation-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .reservation-info {
    width: 100%;
    gap: 10px 0;
  }

  .info-row {
    min-width: 100%;
  }

  .action-area {
    width: 100%;
    text-align: left;
  }

  .delete-btn {
    width: 100%;
  }
}
</style>